package com._21cn.cms.common.utils;

import com._21cn.framework.utils.StringUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Thinkpad on 2017/4/1.
 */
public class DocumentUtil {

    /**
     *  获取文档中完整的文章链接url
     * @param originalUrl
     * @param url
     * @return
     */
    public static String getFullUrl(String originalUrl, String url) {
        String completeUrl = url;
        if (!StringUtil.isEmpty(originalUrl) && !StringUtil.isEmpty(url)
                && !url.contains("http://") && !url.contains("https://")) {
            if (url.startsWith("//")) {
                if(originalUrl.startsWith("https")){
                    completeUrl = "https:" + url;
                }else{
                    completeUrl = "http:" + url;
                }
            } else {
                String domain = getDomain(originalUrl);
                if (url.matches("^[\\.]+/.*")) {
                    String splitStr = regularGroup("^[\\.]+/", url, 0, 0).get(0);
                    if(!StringUtil.isEmpty(splitStr)){
                        completeUrl = getRelativePath(url,originalUrl)+"/"+url.replace(splitStr, "");
                    }
                } else if (!StringUtil.isEmpty(domain) && !url.contains(domain.replace("http://", ""))) {
                    if(url.startsWith("/")){
                        completeUrl = domain +url;
                    }else{
                        completeUrl = domain +"/"+url;
                    }
                } else {
                    completeUrl = "http://" + url;
                }
            }
        }
        return completeUrl;
    }

    /**
     * 根据url获取一级域名
     *
     * @param url
     * @return
     */
    public static String getDomain(String url) {
        if (url == null || url.isEmpty()) {
            return url;
        }
        if (url.startsWith("http://")) {
            url = url.replace("http://", "");
        }
        if (url.startsWith("https://")) {
            url = url.replace("https://", "");
        }
        String domain = "";
        if(!url.contains("/")){
            domain = "http://" + url.split("\\?")[0];
        }else{
            domain = "http://" + url.split("/")[0];
        }
        return domain;
    }

    /**
     * @param pattern
     *            正则表达式
     * @param matcher
     *            目标字符串
     * @param start
     *            截取开始位置
     * @param end
     *            截取结束位置
     * @return  返回一个能匹配到的集合
     */
    public static List<String> regularGroup(String pattern, String matcher, int start, int end) {
        Pattern p = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);
        Matcher m = p.matcher(matcher);
        List<String> strList = new ArrayList<String>();
        while (m.find()) {
            String str = m.group();
            strList.add(str.substring(start, str.length() - end));// 把捕获的数据加入集合
        }
        //如果一个也没匹配到，则赋值空字符串""
        if (strList.size()<1)
            strList.add("");
        return strList;
    }

    /**
     * 根据url相对路径
     * @param url
     *  @param originalUrl
     * @return
     */
    public static String getRelativePath(String url,String originalUrl) {
        if (StringUtil.isEmpty(url)||StringUtil.isEmpty(originalUrl)) {
            return url;
        }
        String key=".";
        int count = 0;
        int index = 0;
        while((index=url.indexOf(key,index))!=-1){
            index = index+key.length();
            count++;
        }
        String http = "http://";
        if(originalUrl.contains("https://")){
            http = "https://";
        }
        String relativePath = http;
        String[] ss = originalUrl.replace(http, "").split("\\?")[0].split("/");
        int len = ss.length-count+1;
        len=len>0?len:1;
        for (int i = 0; i < ss.length&&i < len; i++) {
            relativePath=i==0?relativePath+ss[i]:relativePath+"/"+ss[i];
        }
        return relativePath;
    }


    /**
     * 根据文本取得图片URL链接
     * @param content
     * @return
     */
    public static List<String> getImageUrls(String content){
        Document doc = Jsoup.parse(content);
        Elements imgs =  doc.select("img");
        List<String> urlList = new ArrayList<String>();
        for(Element i:imgs){
            String imgUrl = i.attr("src");
            urlList.add(imgUrl);
        }
        return urlList;
    }
}
